<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {

        Validator::make($request->input(), [
            'email' => ['required', 'exists:users,email'],
            'password' => ['required'],
        ])->validate();

        $user = User::where('email', $request->email)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            // $user->login_count++;
            // $user->save();
            // return ['token' => $user->createToken('auth')->plainTextToken, 'user' => $user];
            return $this->success('登录成功', ['token' => $user->createToken('auth')->plainTextToken, 'user' => $user]);
        }

        throw ValidationException::withMessages(['password' => '密码输入错误']);
    }
}
